/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
  * author: chenYuan , 陈原
 * @License: jcms 商业软件,代码只提供给商业许可的用户
 * @jvm:jdk1.6+  x86/amd64
 *
 */

package jspx.example.test;

import com.github.jspxnet.boot.EnvFactory;
import com.github.jspxnet.boot.environment.Environment;
import com.github.jspxnet.boot.environment.EnvironmentTemplate;
import com.github.jspxnet.boot.environment.Placeholder;
import com.github.jspxnet.enums.RecycleEnumType;
import com.github.jspxnet.json.*;
import com.github.jspxnet.scriptmark.util.ScriptMarkUtil;
import com.github.jspxnet.sober.annotation.*;
import com.github.jspxnet.sober.enums.MappingType;
import com.github.jspxnet.sober.table.OperateTable;
import com.github.jspxnet.txweb.table.PhotoPattern;
import com.github.jspxnet.txweb.table.TreeItem;
import com.github.jspxnet.txweb.turnpage.TurnPageButton;
import com.github.jspxnet.txweb.turnpage.impl.TurnPageButtonImpl;
import com.github.jspxnet.util.StringMap;
import com.github.jspxnet.utils.*;
import jspx.example.test.env.FormatType;
import jspx.example.test.env.Jcms;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: chenYuan
 * date: 2004-4-23
 * Time: 16:10:25
 * HTML 页面列表  jspx.juser.table.HtmlContent
 * jspx.jcms.table.Matter
 */
@EqualsAndHashCode(callSuper = true)
@Data
@Table(name = "jcms_matter", caption = "内容正文")
public class Matter extends OperateTable {
    @Id(auto = true, length = 24, type = IDType.uuid)
    @Column(caption = "ID", length = 32, notNull = true)
    private String id;


    @Column(caption = "专题ID", length = 32)
    private String troopId = StringUtil.empty;

    //用于书目录结构形式
    @Column(caption = "书编号", length = 50, dataType = "isLengthBetween(1,50)")
    private String bookId = StringUtil.empty;

    //附件列表
    @Column(caption = "附件", length = 1200, dataType = "isLengthBetween(0,1200)")
    private String attachments = StringUtil.empty;

    @Column(caption = "文档类型", length = 40, option = "原创;图文;下载;转贴;投票;公文")
    private String docType = StringUtil.empty;

    @Column(caption = "发文编号", length = 50, dataType = "isLengthBetween(0,50)")
    private String documentSerial = StringUtil.empty;

    //形如“000014349/2008-12345”。前段码为信息发布单位的组织机构代码，形如“00001434-9”或者“40000895-X”（在使用中应略去“一”）。
    // 组织机构代码由技术监督部门统一编制。后段码为“4 位年份数字”加上“5位数字流水号”中间用“—”链接。
    //组织机构代码(9)/年(4)-序号(5)
    @Column(caption = "索引号", length = 20, dataType = "isLengthBetween(0,20)")
    private String identifier = StringUtil.empty;

    //信息分类（Category ,算二次分类,也是政府文档的，类别
    @Column(caption = "信息分类", length = 100, dataType = "isLengthBetween(0,50)")
    private String category = StringUtil.empty;

    @Column(caption = "概述", length = 2000, dataType = "isLengthBetween(1,1000)")
    private String description = StringUtil.empty;

    @Column(caption = "颜色", length = 10, dataType = "isLengthBetween(2,4)")
    private String titleColor = StringUtil.empty;

    @Column(caption = "背景色", length = 10, dataType = "isLengthBetween(2,4)")
    private String background = StringUtil.empty;

    @Column(caption = "字体样式", option = "0:默认;1:粗体;2:斜体;3:粗斜体", dataType = "indexOfArray([0,1,2,3])", length = 10, notNull = true)
    private String fontType = "0";

    @Column(caption = "主题", length = 200, dataType = "isLengthBetween(2,100)", notNull = true)
    private String title = StringUtil.empty;

    @Column(caption = "节点ID", length = 50, dataType = "isLengthBetween(1,50)", notNull = true)
    private String nodeId = StringUtil.empty;

    @Nexus(mapping = MappingType.OneToOne, field = "nodeId", targetField = "nodeId", term = "namespace:eq[" + Jcms.namespace + "]", targetEntity = TreeItem.class, delete = false)
    private TreeItem treeItem;

    @Column(caption = "关键字", length = 240, dataType = "isLengthBetween(2,240)", notNull = true)
    private String tags = StringUtil.empty;

    @Column(caption = "来源", length = 100, dataType = "isLengthBetween(1,100)")
    private String origin = StringUtil.empty;

    @Column(caption = "作者", length = 50, dataType = "isLengthBetween(1,50)")
    private String creator = StringUtil.empty;

    @Column(caption = "编辑", length = 50, dataType = "isLengthBetween(1,50)")
    private String editor = StringUtil.empty;

    @Column(caption = "保留字段", length = 200)
    private String fieldExtend = StringUtil.empty;

    @Column(caption = "缩图", length = 200, dataType = "isLengthBetween(1,200)")
    private String images = StringUtil.empty;

    //替代创建日期，提供给政府文档检查使用，此生成日期可改
    @Column(caption = "生成日期", notNull = true)
    private Date creationDate = new Date();


    //根据下边的配置来定义  例如:5:quote 6:电子报 挂接的是Paper  7:投票方式
    @JsonIgnore
    @Column(caption = "引用ID", length = 32)
    private String quoteId = StringUtil.empty;

    //不同的个数注入的不同对象，根据 formatType 来确定
    private Object quoteObject = null;
    //0:html;1:markdown;2:link;3:img;4:layout；5:quote;6:
    //0:普通HTML;1:md格式文档；2:链接方式 3:纯图片;4:图片布局方式  5:引用 6:电子报 7:投票方式
    //如果是两位数,第一位为0，表示网页信息,1:表示公文   10:表示html格式的公文 11:markdown格式公文;12:链接方式公文
    //投票方式主要方便提供类似微信投票的功能
    @Column(caption = "格式", option = "0:html;1:markdown;2:link;3:img;4:layout;5:quote;6:电子报;7:投票;10:公文;12:邮票", notNull = true, defaultValue = "0")
    private int formatType = FormatType.HTML;

    //图片布局模板ID
    @Column(caption = "图片布局模板", defaultValue = "0")
    private long photoPatternId = 0;

    @Nexus(mapping = MappingType.OneToOne, field = "photoPatternId", targetField = "id", term = "namespace:eq[" + Jcms.namespace + "]", targetEntity = PhotoPattern.class)
    private PhotoPattern photoPattern;

    @Column(caption = "内容", length = 10000, dataType = "isLengthBetween(1,99999)", notNull = true)
    private String content = StringUtil.empty;

    @Column(caption = "点击次数", notNull = true)
    private int click = 0;

    @Column(caption = "好评", notNull = true)
    private int goodPoint = 0;

    @Column(caption = "坏评", notNull = true)
    private int poorPoint = 0;

    @Column(caption = "打开方式", length = 10, option = "_self;本页;_bank:新窗口;", dataType = "indexOfArray(['_self','_bank'])", notNull = true, defaultValue = "_self")
    private String target = "_bank";

    @Column(caption = "省份地区", length = 50)
    private String province = StringUtil.empty;

    @Column(caption = "审核", option = "0:初始;1:通过;2:不通过", length = 2, notNull = true)
    private int auditingType = 0;

    @Column(caption = "审核时间", notNull = true)
    private Date auditingDate = new Date();

    @Column(caption = "不通过描述", length = 250)
    private String auditingNote = "";

    //消耗金钱 正文付费
    @Column(caption = "金钱", notNull = true)
    private double amount = 0;

    //消耗积分
    @Column(caption = "积分", notNull = true)
    private int points = 0;

    @JsonIgnore
    @Column(caption = "是否在回收站", length = 2, enumType = RecycleEnumType.class,  notNull = true)
    private int recycleType = RecycleEnumType.NO_RECYCLE.getValue();

    @JsonIgnore
    @Column(caption = "回收时间", notNull = true)
    private Date recycleDate = new Date();

    @JsonIgnore
    @Column(caption = "删除人")
    private long recycleUid = 0;

    @JsonIgnore
    @Column(caption = "步凑", notNull = true)
    private int flowType = 0;

    @Column(caption = "排序", option = "0:默认;2:固顶;4:置顶;8:结对置顶;-1:下沉", notNull = true)
    private int sortType = 0;

    @JsonIgnore
    @Column(caption = "排序时间", notNull = true)
    private Date sortDate = new Date();

    @Column(caption = "发布时间", notNull = true)
    private Date issueDate = new Date();

    @JsonIgnore
    @Column(caption = "最后修改时间", notNull = true)
    private Date lastModerated = new Date();

    @JsonIgnore
    @Column(caption = "过期时间", notNull = true)
    private Date expiredDate = DateUtil.empty;

    @JsonIgnore
    @Column(caption = "修改用户", length = 50)
    private String moderatedName = StringUtil.empty;

    @JsonIgnore
    @Column(caption = "修改Uid")
    private long moderatedUid = 0;

    //及时计算，性能很差
    @Column(caption = "回复数量", notNull = true)
    private int replyCount = 0;

    //作为日历使用
    @JsonIgnore
    @Column(caption = "日期", length = 50, notNull = true)
    private String dateStr = DateUtil.getDateST();

    //为了统计方便
    @JsonIgnore
    @Column(caption = "月份", length = 50, notNull = true)
    private String monthStr = DateUtil.toString(new Date(), "yyyy-MM");

    //为了统计方便
    @JsonIgnore
    @Column(caption = "年份", dataType = "isLengthBetween(2,10)", length = 10, notNull = true)
    private String yearStr = DateUtil.toString(new Date(), "yyyy");

    @JsonIgnore
    @Column(caption = "命名空间", length = 50, dataType = "isLengthBetween(1,50)")
    private String namespace = StringUtil.empty;

    @JsonIgnore
    @Column(caption = "机构ID", length = 32)
    private String organizeId = StringUtil.empty;

    @JsonIgnore
    @Column(caption = "留言板ID", notNull = true)
    private long boardId = 0;

    @JsonIgnore
    private String caption;

    // 文章链接后续可以加一个字段
    private String linkUrl;

    //当为-1的时候显示全部
    private int page = 1;
    private int totalPage = 0;

    //判断是否为手机
    private int browserModel = 0;
    private int photoModel = 0;

    //域名 放入 http://www.jspx.net
    private String hostUrl = StringUtil.empty;

    public Matter() {

    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public String getCaption() {
        return getCaptionFormat("[${page}]");
    }

    /**
     * @param format 格式
     * @return 显示格式化
     * ${m.getCaptionFormat("[${page}]")}
     */
    public String getCaptionFormat(String format) {
        if (getTotalPage() <= 1) {
            return StringUtil.empty;
        }
        if (StringUtil.isNull(format)) {
            return page + "";
        }
        Map<String, Object> valueMap = new HashMap<String, Object>(20);
        valueMap.put("page", page);
        valueMap.put("totalPage", totalPage);
        valueMap.put("id", id);
        valueMap.put("troopId", troopId);
        valueMap.put("bookId", bookId);
        valueMap.put("title", title);
        valueMap.put("docType", docType);
        valueMap.put("goodPoint", goodPoint);
        valueMap.put("poorPoint", poorPoint);
        valueMap.put("background", background);
        valueMap.put("formatType", formatType);
        valueMap.put("fontType", fontType);
        valueMap.put("nodeId", nodeId);
        valueMap.put("namespace", namespace);
        try {
            return EnvFactory.getPlaceholder().processTemplate(valueMap, format);
        } catch (Exception e) {
            return "";
        }
    }

    public String getImageHtml() {
        if (StringUtil.isNull(images)) {
            return StringUtil.empty;
        }
        StringBuilder sb = new StringBuilder();
        if (images.startsWith("/") || images.startsWith("http")) {
            sb.append("<img src=\"").append(images).append("\" title=\"").append(title).append("\" border=0 />");
        } else if (images.startsWith("upload")) {
            sb.append("<img src=\"/jcms/").append(images).append("\" title=\"").append(title).append("\" border=0 />");
        } else if (!images.contains("/")) {
            sb.append("<img src=\"/jcms/").append(images).append("\" title=\"").append(title).append("\" border=0 />");
        } else {
            sb.append("<img src=\"").append(images).append("\" title=\"").append(title).append("\" border=0 />");
        }
        return sb.toString();
    }

    public String[] getImageArray() {
        return HtmlUtil.getTagAttribute(content, "img", "src");
    }

    @JsonField(name = "imageUrl", caption = "图片地址")
    public String getImageUrl() {

        if (StringUtil.isNull(images)) {
            return "/share/pimg/basesys/s_none.gif";
        }
        if (images.contains(".")) {
            return images;
        }
        //转换为完整路径
        String[] imgArray = getImageArray();
        if (!ArrayUtil.isEmpty(imgArray)) {
            return imgArray[0];
        }
        if (StringUtil.isNull(images)) {
            return "/share/pimg/basesys/s_none.gif";
        }
        return images;
    }

    private String getHtml() {
        //markdown 格式支持 begin
        String result = content;
        if (formatType == 1) {
            try {
                result = ScriptMarkUtil.getMarkdownHtml(result);
            } catch (Exception e) {
                return content;
            }
        }
        //markdown 格式支持 end Environment.photoModel
        if (browserModel == 1) {
            return HtmlUtil.getMobileImageFilter(result, URLUtil.getHostUrl(hostUrl));
        }
        return result;
    }


    public String getPageCont() {
        if (getTotalPage() <= 1) {
            return getHtml();
        }
        String[] pages = StringUtil.split(getHtml(), Environment.turnPageMark);
        if (ArrayUtil.isEmpty(pages)) {
            return getHtml();
        }
        if (pages.length >= page) {
            return pages[page - 1];
        }
        return pages[pages.length - 1];
    }

    public int getTotalPage() {

        if (totalPage == 0) {
            totalPage = StringUtil.countMatches(content, Environment.turnPageMark) + 1;
        }
        return totalPage;
    }

    public String getStyle() {
        StringBuilder sb = new StringBuilder();
        if ("1".equals(fontType) || "bold".equalsIgnoreCase(fontType)) {
            sb.append("font-weight:bold;");
        } else if ("2".equals(fontType) || "italic".equalsIgnoreCase(fontType)) {
            sb.append("font-style:italic;");
        } else if ("3".equals(fontType) || "italic".equalsIgnoreCase(fontType)) {
            sb.append("font-weight:bold;font-style:italic;");
        }
        if (!StringUtil.isNull(background)) {
            sb.append("background:").append(background).append(StringUtil.SEMICOLON);
        }
        if (!StringUtil.isNull(titleColor)) {
            sb.append("color:#").append(StringUtil.replace(titleColor, "#", "")).append(StringUtil.SEMICOLON);
        }
        //0:默认;1:粗体;2:斜体;3:粗斜体
        return sb.toString();
    }

    public void setIssueDate(Date issueDate) {
        this.issueDate = issueDate;
        this.dateStr = DateUtil.toString(new Date(), DateUtil.DAY_FORMAT);
        this.monthStr = DateUtil.toString(new Date(), "yyyy-MM");
        this.yearStr = DateUtil.toString(new Date(), "yyyy");
    }

    public int getReplyCount() {
        return replyCount;
    }

    public void setReplyCount(int replyCount) {
        this.replyCount = replyCount;
    }

    @JsonField(name = "nodeCaption", caption = "栏目名称")
    public String getNodeCaption() {
        if (treeItem != null) {
            return treeItem.getCaption();
        }
        return StringUtil.empty;
    }


    public String getTurnPage() throws Exception {
        return getTurnPage("docturnpage.ftl");
    }


    public String getTurnPage(String template) throws Exception {

        int totalPage = getTotalPage();
        if (totalPage <= 1) {
            return StringUtil.empty;
        }
        TurnPageButton turnPage = new TurnPageButtonImpl();
        turnPage.setCount(1);
        turnPage.setQuerystring("id=" + id);
        turnPage.setTotalCount(totalPage);
        turnPage.setTotalPage(totalPage);
        turnPage.setCurrentPage(page);
        turnPage.setFileName(template);
        return turnPage.getTurnPage();
    }

    public String getAttachmentJson() throws JSONException {
        EnvironmentTemplate environmentTemplate = EnvFactory.getEnvironmentTemplate();
        String filterSuffix = environmentTemplate.getString(Environment.filterSuffix);
        return getAttachmentJson(filterSuffix);
    }

    public String getAttachmentJson(String suffix) {
        if (StringUtil.isNull(attachments)) {
            return "[]";
        }
        StringMap<String, String> map = new StringMap();
        map.setKeySplit("=");
        map.setLineSplit(StringUtil.CRLF);
        map.setString(attachments);
        JSONArray jsonArray = new JSONArray();
        for (String key : map.keySet()) {
            String value = map.get(key);
            String link = StringUtil.trim(StringUtil.getElementValue(value));
            String title = StringUtil.trim(StringUtil.getElementName(value));
            JSONObject json = new JSONObject();
            json.put("id", key);
            json.put("title", title);
            //browserModel
            if (photoModel == 0) {
                if (browserModel == 0) {
                    if (link.startsWith("/")) {
                        json.put("img", link);
                        json.put("image", link);
                        json.put("link", hostUrl + link);
                    } else {
                        json.put("img", "/" + Jcms.namespace + "/" + link);
                        json.put("link", hostUrl + "/" + Jcms.namespace + "/" + link);
                    }
                } else if (browserModel == 1) {
                    if (link.startsWith("/")) {
                        json.put("img", FileUtil.getMobileFileName(link));
                        json.put("image", FileUtil.getMobileFileName(link));
                        json.put("link", hostUrl + FileUtil.getMobileFileName(link));
                    } else {
                        json.put("img", "/" + Jcms.namespace + "/" + FileUtil.getMobileFileName(link));
                        json.put("image", "/" + Jcms.namespace + "/" + FileUtil.getMobileFileName(link));
                        json.put("link", hostUrl + FileUtil.getMobileFileName(link));
                    }
                }
            } else {
                json.put("img", "/" + Jcms.namespace + "/download/" + key + "." + suffix);
                json.put("image", "/" + Jcms.namespace + "/download/" + key + "." + suffix);
                json.put("link", hostUrl + "/" + Jcms.namespace + "/download/" + key + "." + suffix);
            }
            jsonArray.put(json);
        }
        return jsonArray.toString();
    }

    /**
     * @return 得到模板
     */
    public String getPhotoLayoutContent() {
        if (4 != formatType || photoPatternId < 1 || photoPattern == null || StringUtil.isNull(photoPattern.getContent())) {
            return StringUtil.empty;
        }

        EnvironmentTemplate environmentTemplate = EnvFactory.getEnvironmentTemplate();
        String filterSuffix = environmentTemplate.getString(Environment.filterSuffix);
        if (hostUrl == null) {
            hostUrl = StringUtil.empty;
        }
        StringMap<String, String> map = new StringMap();
        map.setKeySplit("=");
        map.setLineSplit(StringUtil.CRLF);
        map.setString(attachments);
        if (map.size() <= 0 || photoPattern.getPhotoNumber() > map.size()) {
            return "布局模板支持为" + photoPattern.getPhotoNumber() + "不等于图片数量" + map.size();
        }

        Map<String, Object> valueMap = new HashMap<String, Object>();
        int i = 0;
        for (String key : map.keySet()) {
            i++;
            String caption = map.get(key);
            valueMap.put("index", i);
            valueMap.put("sort", i + 1);

            valueMap.put("id" + i, key == null ? StringUtil.empty : key);
            valueMap.put("title" + i, StringUtil.getElementName(caption));
            String link = StringUtil.getElementValue(StringUtil.trim(caption));
            if (photoModel == 0) {
                if (browserModel == 0) {

                    if (link.startsWith("/")) {
                        valueMap.put("img" + i, link);
                        valueMap.put("link" + i, hostUrl + link);
                    } else {
                        valueMap.put("img" + i, "/" + Jcms.namespace + "/" + link);
                        valueMap.put("link" + i, hostUrl + "/" + Jcms.namespace + "/" + link);
                    }
                } else if (browserModel == 1) {
                    if (link.startsWith("/")) {
                        valueMap.put("img" + i, FileUtil.getMobileFileName(link));
                        valueMap.put("link" + i, hostUrl + FileUtil.getMobileFileName(link));
                    } else {
                        valueMap.put("img" + i, "/" + Jcms.namespace + "/" + FileUtil.getMobileFileName(link));
                        valueMap.put("link" + i, hostUrl + FileUtil.getMobileFileName(link));
                    }
                }
            } else {
                valueMap.put("img" + i, "/" + Jcms.namespace + "/download/" + key + "." + filterSuffix);
                valueMap.put("link" + i, hostUrl + "/" + Jcms.namespace + "/download/" + key + "." + filterSuffix);
            }
            if (i > 10) {
                break;
            }
        }
        Placeholder placeholder = EnvFactory.getPlaceholder();
        try {
            if (i > 10) {
                StringBuilder sb = new StringBuilder();
                sb.append(placeholder.processTemplate(valueMap, photoPattern.getContent()));
                sb.append(StringUtil.CRLF);
                i = 0;
                for (String key : map.keySet()) {
                    valueMap.clear();
                    i++;
                    if (i > 10) {

                        if (StringUtil.isNull(key)) {
                            continue;
                        }
                        valueMap.put("id1", key);
                        String caption = map.get(key);
                        valueMap.put("title1", FileUtil.getNamePart(StringUtil.getElementName(caption)));
                        String value = StringUtil.getElementValue(caption);
                        if (photoModel == 0) {
                            if (browserModel == 0) {
                                valueMap.put("img1", value);
                                valueMap.put("link1", hostUrl + value);
                            } else if (browserModel == 1) {
                                if (value.startsWith("/")) {
                                    valueMap.put("img1", FileUtil.getMobileFileName(value));
                                    valueMap.put("link1", hostUrl + FileUtil.getMobileFileName(value));
                                } else {
                                    valueMap.put("img1", "/" + Jcms.namespace + "/" + FileUtil.getMobileFileName(value));
                                    valueMap.put("link1", hostUrl + "/" + Jcms.namespace + "/" + FileUtil.getMobileFileName(value));
                                }
                            }
                        } else {
                            valueMap.put("img1", "/" + Jcms.namespace + "/download/" + key + "." + filterSuffix);
                            valueMap.put("link1", hostUrl + "/" + Jcms.namespace + "/download/" + key + "." + filterSuffix);
                        }
                        sb.append(placeholder.processTemplate(valueMap, "<div class=\"row\"><div class=\"p_m1\"><img src=\"${img1}\" ref=\"${id1}\" title=\"${title1}\" ></div></div>\r\n"));
                    }
                }
                return sb.toString();
            } else {
                return placeholder.processTemplate(valueMap, photoPattern.getContent());
            }
        } catch (Exception e) {
            return "图片布局模板错误,matterId=" + id + " photoPatternId=" + photoPatternId + "<br>" + StringUtil.toBrLine(e.getLocalizedMessage());
        }
    }

    public int getAttachmentSize() {
        return StringUtil.countMatches(attachments, StringUtil.CR);
    }

    public Matter(String text) {
        title = StringUtil.trim(StringUtil.substringBetween(text, "<title>", "</title>"));
        formatType = StringUtil.toInt(StringUtil.trim(StringUtil.substringBetween(text, "<formatType>", "</formatType>")));
        origin = StringUtil.trim(StringUtil.substringBetween(text, "<origin>", "</origin>"));
        creator = StringUtil.trim(StringUtil.substringBetween(text, "<creator>", "</creator>"));
        documentSerial = StringUtil.trim(StringUtil.substringBetween(text, "<serial>", "</serial>"));
        if (StringUtil.isNull(documentSerial)) {
            documentSerial = StringUtil.trim(StringUtil.substringBetween(text, "<documentSerial>", "</documentSerial>"));
        }
        content = StringUtil.trim(StringUtil.substringBetween(text, "<cont>", "</cont>"));
        if (StringUtil.isNull(content)) {
            content = StringUtil.trim(StringUtil.substringBetween(text, "<content>", "</content>"));
        }

        editor = StringUtil.trim(StringUtil.substringBetween(text, "<editor", "</editor>"));
        tags = StringUtil.trim(StringUtil.substringBetween(text, "<tags>", "</tags>"));
        identifier = StringUtil.trim(StringUtil.substringBetween(text, "<identifier>", "</identifier>"));
        category = StringUtil.trim(StringUtil.substringBetween(text, "<category>", "</category>"));
        docType = StringUtil.trim(StringUtil.substringBetween(text, "<docType>", "</docType>"));
        sortType = StringUtil.toInt(StringUtil.trim(StringUtil.substringBetween(text, "<sort>", "</sort>")));
        String files = StringUtil.substringBetween(text, "<file>", "</file>");
        if (StringUtil.isNull(files)) {
            files = StringUtil.substringBetween(text, "<attachments>", "</attachments>");
        }
        attachments = files;

        nodeId = StringUtil.substringBetween(text, "<nodeId>", "</nodeId>");

        String creationDateStr = StringUtil.substringBetween(text, "<creationDate>", "</creationDate>");
        if (!StringUtil.isNull(creationDateStr) && creationDateStr.length() > 5) {
            try {
                creationDate = StringUtil.getDate(creationDateStr);
            } catch (Exception e) {
                creationDate = new Date();
            }
        }
        String issueDateStr = StringUtil.substringBetween(text, "<issueDate>", "</issueDate>");
        if (!StringUtil.isNull(issueDateStr) && issueDateStr.length() > 5) {
            try {
                issueDate = StringUtil.getDate(issueDateStr);
            } catch (Exception e) {
                issueDate = new Date();
            }
        }
        images = StringUtil.trim(StringUtil.substringBetween(text, "<img>", "</img>"));
        if (StringUtil.isNull(images)) {
            images = StringUtil.trim(StringUtil.substringBetween(text, "<images>", "</images>"));
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("<matter id=\"").append(id).append("\">").append(StringUtil.CRLF);
        sb.append("<formatType>").append(formatType).append("</formatType>").append(StringUtil.CRLF);
        sb.append("<serial>").append(documentSerial).append("</serial>").append(StringUtil.CRLF);
        sb.append("<images>").append(images).append("</images>").append(StringUtil.CRLF);
        sb.append("<title>").append(title).append("</title>").append(StringUtil.CRLF);
        sb.append("<tags>").append(tags).append("</tags>").append(StringUtil.CRLF);
        sb.append("<cont>").append(content).append("</cont>").append(StringUtil.CRLF);
        sb.append("<origin>").append(origin).append("</origin>").append(StringUtil.CRLF);
        sb.append("<creator>").append(creator).append("</creator>").append(StringUtil.CRLF);
        sb.append("<editor>").append(editor).append("</editor>").append(StringUtil.CRLF);
        sb.append("<identifier>").append(identifier).append("</identifier>").append(StringUtil.CRLF);
        sb.append("<category>").append(category).append("</category>").append(StringUtil.CRLF);
        sb.append("<docType>").append(docType).append("</docType>").append(StringUtil.CRLF);
        sb.append("<files>").append(attachments).append("</files>").append(StringUtil.CRLF);
        sb.append("<nodeId>").append(nodeId).append("</nodeId>").append(StringUtil.CRLF);
        sb.append("<sort>").append(nodeId).append("</sort>").append(StringUtil.CRLF);
        sb.append("<creationDate>").append(DateUtil.toString(creationDate, DateUtil.ST_FORMAT)).append("</creationDate>").append(StringUtil.CRLF);
        sb.append("<issueDate>").append(DateUtil.toString(issueDate, DateUtil.ST_FORMAT)).append("</issueDate>").append(StringUtil.CRLF);
        sb.append("</matter>").append(StringUtil.CRLF);
        return sb.toString();
    }
}